<template>
  <view class="send-page">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="nav-left" @click="goBack">
        <u-icon name="arrow-left" color="#ffffff" size="24"></u-icon>
      </view>
      <view class="nav-center">
        <text class="nav-title">发文管理</text>
      </view>
      <view class="nav-right"> </view>
    </view>

    <!-- Tab 切换（根据权限显示） -->
    <view class="tab-switch" v-if="availableTabs.length > 0">
      <scroll-view class="tab-scroll" scroll-x="true">
        <view class="tab-list">
          <view
            class="tab-item"
            v-for="tab in availableTabs"
            :key="tab.key"
            :class="{ active: activeTab === tab.key }"
            @click="switchTab(tab.key)"
          >
            <text class="tab-text">{{ tab.label }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 搜索区域 -->
    <view class="search-section" v-if="activeTab === 'my'">
      <view class="search-form">
        <input class="search-input" v-model="searchForm.title" placeholder="请输入公文标题" />
        <view class="search-buttons">
          <text class="search-btn" @click="handleSearch">查询</text>
          <text class="reset-btn" @click="handleReset">重置</text>
        </view>
      </view>
    </view>

    <!-- 状态切换（只在我的发文显示） -->
    <view class="status-switch" v-if="activeTab === 'my'">
      <view
        class="status-tab"
        :class="{ active: searchForm.state === 1 }"
        @click="handleStateSwitch('active')"
      >
        <u-icon
          name="clock"
          :color="searchForm.state === 1 ? '#ffffff' : '#666666'"
          size="18"
        ></u-icon>
        <text class="tab-text">进行中</text>
      </view>
      <view
        class="status-tab"
        :class="{ active: searchForm.state === 0 }"
        @click="handleStateSwitch('completed')"
      >
        <u-icon
          name="checkmark-circle"
          :color="searchForm.state === 0 ? '#ffffff' : '#666666'"
          size="18"
        ></u-icon>
        <text class="tab-text">已完结</text>
      </view>
    </view>

    <!-- 发文列表 -->
    <view class="list-section">
      <view class="list-header">
        <text class="list-title">{{ listTitle }}</text>
        <text class="list-count">共{{ pagination.total }}条</text>
      </view>

      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <text class="loading-text">加载中...</text>
      </view>

      <view class="send-list" v-else-if="documentList.length > 0">
        <view class="send-item" v-for="item in documentList" :key="item.id">
          <view class="item-header">
            <view class="item-title">
              <text class="title-text">{{ item.title || '无标题' }}</text>
              <view
                :class="[
                  item.bizCategory === '党务发文' ? 'category-badge-party' : 'category-badge',
                ]"
                v-if="item.bizCategory"
              >
                <text class="badge-text">{{ item.bizCategory }}</text>
              </view>
            </view>
            <text class="item-time">{{ formatDateTime(item.createdAt) }}</text>
          </view>
          <view class="item-content">
            <text class="item-desc">拟稿部门：{{ item.applicantDeptName || '未知' }}</text>
            <text class="item-desc">拟稿人：{{ item.applicantName || '未知' }}</text>
            <text class="item-desc" v-if="activeTab === 'my' && searchForm.state === 1"
              >当前步骤：{{ item.currentStepName || `步骤${item.currentStep}` }}</text
            >
            <text class="item-desc" v-if="activeTab === 'todo'"
              >当前步骤：{{ item.currentStepName || `步骤${item.currentStep}` }}</text
            >
            <text class="item-desc" v-if="activeTab === 'todo'"
              >下一步骤：{{ item.nextStepName || '-' }}</text
            >
          </view>
          <view class="item-footer">
            <view class="item-info">
              <view class="reject-badge" v-if="activeTab === 'my' && item.status === 'reject'">
                <text class="badge-text">被退回</text>
              </view>
              <view
                class="distribute-status"
                :class="{ distributed: item.isDistributed === 1 }"
                v-if="activeTab === 'my'"
              >
                <text class="status-text">{{ getDistributeStatusText(item.isDistributed) }}</text>
              </view>
            </view>
            <view class="item-actions">
              <text class="action-btn" @click.stop="viewDetail(item)">查看</text>
              <text
                class="action-btn primary"
                v-if="activeTab === 'my' && item.isDistributed === 1"
                @click.stop="showDistribute(item)"
              >
                分发信息
              </text>
              <text
                class="action-btn primary"
                v-if="activeTab === 'todo'"
                @click.stop="handleApprove(item)"
              >
                审批
              </text>
              <text
                class="action-btn primary"
                v-if="activeTab === 'redHeader'"
                @click.stop="handleRedHeader(item)"
              >
                套红
              </text>
              <text
                class="action-btn primary"
                v-if="activeTab === 'seal'"
                @click.stop="handleSeal(item)"
              >
                签章
              </text>
              <text
                class="action-btn primary"
                v-if="activeTab === 'distribute'"
                @click.stop="handleDistribute(item)"
              >
                分发
              </text>
            </view>
          </view>
        </view>
      </view>

      <view class="empty-state" v-else>
        <text class="empty-icon">📤</text>
        <text class="empty-text">暂无发文数据</text>
      </view>

      <!-- 分页 -->
      <view class="pagination-section" v-if="pagination.total > 0">
        <view class="pagination-info">
          <text
            >共{{ pagination.total }}条，第{{ pagination.current }}/{{
              Math.ceil(pagination.total / pagination.size)
            }}页</text
          >
        </view>
        <view class="pagination-buttons">
          <text
            class="page-btn"
            :class="{ disabled: pagination.current <= 1 }"
            @click="handlePrevPage"
          >
            上一页
          </text>
          <text
            class="page-btn"
            :class="{
              disabled: pagination.current >= Math.ceil(pagination.total / pagination.size),
            }"
            @click="handleNextPage"
          >
            下一页
          </text>
        </view>
      </view>
    </view>

    <!-- 印章选择器 -->
    <SealSelector
      :visible="sealSelectorVisible"
      @update:visible="sealSelectorVisible = $event"
      @confirm="handleSealConfirm"
    />

    <!-- 分发选择器 -->
    <DistributeSelector
      :visible="distributeSelectorVisible"
      @update:visible="distributeSelectorVisible = $event"
      @confirm="handleDistributeConfirm"
    />

    <!-- 分发信息展示 -->
    <DistributeInfo
      :visible="distributeInfoVisible"
      :externalRecords="externalDistributeRecords"
      :internalRecords="internalDistributeRecords"
      @update:visible="distributeInfoVisible = $event"
      @close="handleDistributeInfoClose"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import {
  getAllDocumentsall,
  getDocumentDistributions,
  getInternalDocumentDistributions,
  getCurrentUserPendingDocuments,
  getApprovalDocumentRecords,
  getCurrentRedHeaderDocuments,
  getCurrentSealDocuments,
  submitDocumentApproval,
  applyRedHeader,
  applySeal,
  distributeDocument,
  type DocumentQueryParams,
  type DocumentItem,
  type SealInfo,
  type DocumentDistributePayload,
} from '@/Api/document'
import { UserManager } from '@/utils/user'
import SealSelector from '@/components/SealSelector.vue'
import DistributeSelector from '@/components/DistributeSelector.vue'
import DistributeInfo from '@/components/DistributeInfo.vue'

// 页面参数（从URL接收）
const pageOptions = ref<any>({})

// 当前激活的tab
const activeTab = ref<'my' | 'todo' | 'redHeader' | 'seal' | 'distribute'>('my')

// 页面标题
const pageTitle = computed(() => {
  const titleMap = {
    my: '我的发文',
    todo: '待审批',
    redHeader: '套红',
    seal: '签章',
    distribute: '分发',
  }
  return titleMap[activeTab.value]
})

// 列表标题
const listTitle = computed(() => {
  const titleMap = {
    my: '发文列表',
    todo: '待审批列表',
    redHeader: '待套红列表',
    seal: '待签章列表',
    distribute: '待分发列表',
  }
  return titleMap[activeTab.value]
})

// 加载状态
const loading = ref(false)

// 搜索表单
const searchForm = ref<DocumentQueryParams>({
  title: '',
  applicantId: undefined,
  state: 1, // 0-已完结 1-进行中
})

// 移除 todoApprovalState，待审批tab只显示待审批数据

// 分页数据
const pagination = ref({
  current: 1,
  size: 20,
  total: 0,
})

// 发文列表数据
const documentList = ref<DocumentItem[]>([])

// 分发信息弹窗
const distributeVisible = ref(false)
const currentDistributeItem = ref<DocumentItem | null>(null)
const externalDistributeRecords = ref<any[]>([])
const internalDistributeRecords = ref<any[]>([])

// 分发信息展示弹窗
const distributeInfoVisible = ref(false)

// 印章选择器
const sealSelectorVisible = ref(false)
const currentSealDocument = ref<DocumentItem | null>(null)
const selectedSeal = ref<SealInfo | null>(null)

// 分发选择器
const distributeSelectorVisible = ref(false)
const currentDistributeDocument = ref<DocumentItem | null>(null)

// 用户菜单权限
const userMenuPaths = ref<string[]>([])

// 检查用户是否有任一菜单权限
const hasAnyMenuPermission = (menuPaths: string[]): boolean => {
  return menuPaths.some((menuPath) => userMenuPaths.value.includes(menuPath))
}

// 可用的 Tabs（根据权限过滤）
const availableTabs = computed(() => {
  const allTabs = [
    {
      key: 'my',
      label: '我的发文',
      requiredMenuPaths: ['/document', '/document/draft'],
    },
    {
      key: 'todo',
      label: '待审批',
      requiredMenuPaths: ['/document/todo', '/document/approval'],
    },
    {
      key: 'redHeader',
      label: '套红',
      requiredMenuPaths: ['/document/red-header'],
    },
    {
      key: 'seal',
      label: '签章',
      requiredMenuPaths: ['/document/seal'],
    },
    {
      key: 'distribute',
      label: '分发',
      requiredMenuPaths: ['/document/distribute'],
    },
  ]

  return allTabs.filter((tab) => {
    return hasAnyMenuPermission(tab.requiredMenuPaths)
  })
})

// 获取分发状态文本
const getDistributeStatusText = (isDistributed: number | undefined): string => {
  if (isDistributed === 1) return '已分发'
  return '未分发'
}

// 格式化日期时间
const formatDateTime = (dateTime?: string) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}/${month}/${day}`
}

// Tab 切换
const switchTab = (tab: string) => {
  console.log(`[switchTab] 切换到 ${tab}`)
  activeTab.value = tab as 'my' | 'todo' | 'redHeader' | 'seal' | 'distribute'
  searchForm.value.title = ''
  searchForm.value.state = 1
  pagination.value.current = 1
  loadData()
}

// 状态切换（只在"我的发文"tab中使用）
const switchState = (state: number) => {
  console.log(`[switchState] 状态切换到 ${state === 1 ? '进行中' : '已完结'}`)
  searchForm.value.state = state
  pagination.value.current = 1
  loadData() // 直接调用 loadData，不需要 watch
}

// 状态切换处理（只支持我的发文）
const handleStateSwitch = (type: 'active' | 'completed') => {
  if (activeTab.value === 'my') {
    // 我的发文：active=进行中(1)，completed=已完结(0)
    switchState(type === 'active' ? 1 : 0)
  }
}

// 搜索
const handleSearch = () => {
  console.log('[handleSearch] 执行搜索，只调用 loadData()')
  pagination.value.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  console.log('[handleReset] 重置搜索，只调用 loadData()')
  searchForm.value.title = ''
  pagination.value.current = 1
  loadData()
}

// 返回上一页
const goBack = () => {
  const pages = getCurrentPages()
  console.log('[goBack] 当前页面栈数量:', pages.length)

  // 如果页面栈只有1个页面，说明无法返回，直接跳转到首页
  if (pages.length <= 1) {
    console.log('[goBack] 页面栈只有1个，跳转到首页')
    uni.reLaunch({
      url: '/pages/index/index',
    })
  } else {
    // 有多个页面，执行返回操作
    console.log('[goBack] 执行返回操作')
    uni.navigateBack({
      delta: 1,
    })
  }
}

// 添加发文
const addSend = () => {
  uni.navigateTo({
    url: '/pages/document/send/create',
    fail: () => {
      uni.showToast({
        title: '页面开发中',
        icon: 'none',
      })
    },
  })
}

// 查看详情
const viewDetail = (item: DocumentItem) => {
  console.log('[viewDetail] 点击查看详情:', item)

  // 检查 item.id 是否有效
  if (!item || !item.id) {
    console.error('[viewDetail] 无效的公文数据:', item)
    uni.showToast({
      title: '公文ID无效',
      icon: 'none',
    })
    return
  }

  // 根据当前tab决定source参数
  let source = 'view' // 默认为查看模式
  if (activeTab.value === 'todo') {
    // 待审批tab：只有待审批数据
    source = 'todo' // 待审批 - 显示操作按钮
  } else if (activeTab.value === 'redHeader') {
    source = 'redHeader' // 待套红
  } else if (activeTab.value === 'seal') {
    source = 'seal' // 待签章
  } else if (activeTab.value === 'distribute') {
    source = 'distribute' // 待分发
  }

  // 手动构建URL参数（兼容uni-app所有环境）
  const queryParams: string[] = []
  queryParams.push(`id=${encodeURIComponent(String(item.id))}`)
  queryParams.push(`source=${encodeURIComponent(source)}`)

  // 如果是待审批模式，传递步骤信息
  if (activeTab.value === 'todo') {
    if (item.currentStepName) {
      queryParams.push(`currentStepName=${encodeURIComponent(item.currentStepName)}`)
    }
    if (item.currentStep !== undefined) {
      queryParams.push(`currentStep=${encodeURIComponent(String(item.currentStep))}`)
    }
    if (item.nextStepName) {
      queryParams.push(`nextStepName=${encodeURIComponent(item.nextStepName)}`)
    }
    if (item.issueNumberApproval !== undefined) {
      queryParams.push(
        `issueNumberApproval=${encodeURIComponent(String(item.issueNumberApproval))}`,
      )
    }
  }

  const targetUrl = `/pages/document/send/detail?${queryParams.join('&')}`

  console.log(`[viewDetail] 跳转URL (source=${source}):`, targetUrl)

  uni.navigateTo({
    url: targetUrl,
    success: () => {
      console.log('[viewDetail] 页面跳转成功')
    },
    fail: (err) => {
      console.error('[viewDetail] 页面跳转失败:', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none',
      })
    },
  })
}

// 显示分发信息
const showDistribute = async (item: DocumentItem) => {
  try {
    uni.showLoading({ title: '加载中...' })

    // 并行获取外部发文和内部分发信息
    const [externalResp, internalResp] = await Promise.all([
      getDocumentDistributions(item.id),
      getInternalDocumentDistributions(item.id),
    ])

    uni.hideLoading()

    // 处理外部发文分发记录
    if (externalResp.code === 200) {
      const externalRaw = externalResp.data
      const externalList = Array.isArray(externalRaw)
        ? externalRaw
        : Array.isArray(externalRaw?.records)
        ? externalRaw.records
        : []

      externalDistributeRecords.value = externalList
    } else {
      externalDistributeRecords.value = []
    }

    // 处理内部分发记录
    if (internalResp.code === 200) {
      const internalList = internalResp.data || []

      // 格式化内部分发记录
      const formattedInternalList = internalList.map((item: any) => ({
        id: item.id,
        companyName: item.receiveDeptName,
        viewStatus: item.isRead,
        viewerName: item.receiveUserName,
        viewerDeptName: item.receiveDeptName,
        viewedAt: item.readAt,
        createdAt: item.createdAt,
      }))

      internalDistributeRecords.value = formattedInternalList
    } else {
      internalDistributeRecords.value = []
    }

    currentDistributeItem.value = item

    // 显示分发信息
    // 按创建时间排序
    externalDistributeRecords.value.sort(
      (a: any, b: any) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
    )
    internalDistributeRecords.value.sort(
      (a: any, b: any) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
    )

    // 显示分发信息弹窗
    distributeInfoVisible.value = true
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '获取分发记录失败',
      icon: 'none',
    })
  }
}

// 关闭分发信息弹窗
const handleDistributeInfoClose = () => {
  distributeInfoVisible.value = false
}

// 处理审批 - 跳转到详情页进行审批
const handleApprove = (item: DocumentItem) => {
  console.log('[handleApprove] 跳转到详情页审批:', item)

  // 跳转到详情页，并标记为审批模式
  viewDetail(item)
}

// 处理套红
const handleRedHeader = async (item: DocumentItem) => {
  try {
    const result = await uni.showModal({
      title: '套红确认',
      content: `确定要对《${item.title}》进行套红操作吗？`,
    })

    if (result.confirm) {
      uni.showLoading({ title: '套红中...' })

      const redHeaderFilePath =
        item.redHeaderFilePath || `/uploads/red-header/${item.id}-${Date.now()}.docx`
      const bizCategory = item.bizCategory || ''

      const response = await applyRedHeader(item.id, redHeaderFilePath, bizCategory)

      uni.hideLoading()

      if (response.code === 200) {
        uni.showToast({
          title: '套红成功',
          icon: 'success',
        })
        loadData()
      } else {
        throw new Error(response.message || '套红失败')
      }
    }
  } catch (error: any) {
    uni.hideLoading()
    uni.showToast({
      title: error.message || '套红失败',
      icon: 'none',
    })
  }
}

// 处理签章
const handleSeal = (item: DocumentItem) => {
  console.log('[handleSeal] 打开印章选择器:', item)
  currentSealDocument.value = item
  selectedSeal.value = null
  sealSelectorVisible.value = true
}

// 确认选择印章并执行签章
const handleSealConfirm = async (seal: SealInfo) => {
  console.log('[handleSealConfirm] 选择的印章:', seal)

  if (!currentSealDocument.value) {
    uni.showToast({
      title: '未找到要签章的公文',
      icon: 'none',
    })
    return
  }

  selectedSeal.value = seal

  try {
    // 弹出意见输入框
    // const result = await uni.showModal({
    //   title: '签章确认',
    //   content: `确定要使用 ${seal.sealName} 对《${currentSealDocument.value.title}》进行签章吗？`,
    //   editable: true,
    //   placeholderText: '请输入签章意见（选填）',
    // })

    // if (result.confirm) {
    uni.showLoading({ title: '签章中...' })

    const opinion = '已盖章'

    console.log('[handleSealConfirm] 签章参数:', {
      id: currentSealDocument.value.id,
      sealId: seal.id,
      sealName: seal.sealName,
      opinion,
    })

    const response = await applySeal(currentSealDocument.value.id, seal.id, opinion)

    uni.hideLoading()

    if (response.code === 200) {
      uni.showToast({
        title: '签章成功',
        icon: 'success',
      })
      // 刷新列表
      loadData()
    } else {
      throw new Error(response.message || '签章失败')
    }
    // }
  } catch (error: any) {
    uni.hideLoading()
    console.error('[handleSealConfirm] 签章失败:', error)
    uni.showToast({
      title: error.message || '签章失败',
      icon: 'none',
    })
  } finally {
    currentSealDocument.value = null
    selectedSeal.value = null
  }
}

// 处理分发
const handleDistribute = (item: DocumentItem) => {
  console.log('[handleDistribute] 打开分发选择器:', item)
  currentDistributeDocument.value = item
  distributeSelectorVisible.value = true
}

// 确认分发
const handleDistributeConfirm = async (data: any) => {
  console.log('[handleDistributeConfirm] 分发数据:', data)

  if (!currentDistributeDocument.value) {
    uni.showToast({
      title: '未找到要分发的公文',
      icon: 'none',
    })
    return
  }

  try {
    uni.showLoading({ title: '分发中...' })

    // 分别处理外部和内部分发
    let externalSuccess = false
    let internalSuccess = false

    // 外部单位分发
    if (data.enableExternal && data.selectedCompanies.length > 0) {
      const externalPayload: DocumentDistributePayload = {
        documentId: currentDistributeDocument.value.id,
        documentTitle: currentDistributeDocument.value.title || '',
        distributeType: 'external',
        targetCompanyIds: data.selectedCompanies,
      }

      console.log('[handleDistributeConfirm] 外部单位分发:', externalPayload)
      const resp = await distributeDocument(externalPayload)

      if (resp.code === 200) {
        externalSuccess = true
      } else {
        throw new Error(resp.message || '外部单位分发失败')
      }
    } else {
      externalSuccess = true // 未启用视为成功
    }

    // 内部部门分发
    if (data.enableInternal && data.selectedDepartments.length > 0) {
      const internalPayload: DocumentDistributePayload = {
        documentId: currentDistributeDocument.value.id,
        documentTitle: currentDistributeDocument.value.title || '',
        distributeType: 'internal',
        targetDepartments: data.selectedDepartments,
      }

      console.log('[handleDistributeConfirm] 内部部门分发:', internalPayload)
      const resp = await distributeDocument(internalPayload)

      if (resp.code === 200) {
        internalSuccess = true
      } else {
        throw new Error(resp.message || '内部部门分发失败')
      }
    } else {
      internalSuccess = true // 未启用视为成功
    }

    uni.hideLoading()

    // 显示结果
    if (externalSuccess && internalSuccess) {
      uni.showToast({
        title: '分发成功',
        icon: 'success',
        duration: 1500,
      })

      // 刷新列表
      loadData()
    } else {
      throw new Error('部分分发失败')
    }
  } catch (error: any) {
    uni.hideLoading()
    console.error('[handleDistributeConfirm] 分发失败:', error)
    uni.showToast({
      title: error.message || '分发失败',
      icon: 'none',
    })
  } finally {
    currentDistributeDocument.value = null
  }
}

// 分页处理
const handlePrevPage = () => {
  if (pagination.value.current > 1) {
    pagination.value.current--
    loadData()
  }
}

const handleNextPage = () => {
  const totalPages = Math.ceil(pagination.value.total / pagination.value.size)
  if (pagination.value.current < totalPages) {
    pagination.value.current++
    loadData()
  }
}

// 加载数据（单次请求）
const loadData = async () => {
  try {
    loading.value = true
    console.log(`[loadData] 开始加载数据 - Tab: ${activeTab.value}`)

    // 检查当前 tab 是否有权限
    const hasPermission = availableTabs.value.some((tab) => tab.key === activeTab.value)
    if (!hasPermission) {
      console.warn(`[loadData] 当前tab无权限: ${activeTab.value}，停止加载数据`)
      loading.value = false
      documentList.value = []
      pagination.value.total = 0
      uni.showToast({
        title: '暂无访问权限',
        icon: 'none',
      })
      return
    }

    if (activeTab.value === 'my') {
      // 我的发文 - 只请求当前状态的列表数据（1次请求）
      const userInfo = UserManager.getFullUserInfo()
      const applicantId = userInfo.id ? Number(userInfo.id) : undefined

      const params: DocumentQueryParams = {
        current: pagination.value.current,
        size: pagination.value.size,
        applicantId: applicantId,
        title: searchForm.value.title || undefined,
        state: searchForm.value.state,
      }

      const response = await getAllDocumentsall(params)
      if (response.code === 200) {
        documentList.value = response.data.records || []
        pagination.value.total = response.data.total || 0
      }
    } else if (activeTab.value === 'todo') {
      // 待审批 - 只获取当前用户待审批的公文
      const response = await getCurrentUserPendingDocuments(
        pagination.value.current,
        pagination.value.size,
        searchForm.value.title,
      )
      if (response.code === 200) {
        documentList.value = response.data.records || []
        pagination.value.total = response.data.total || 0
      }
    } else if (activeTab.value === 'redHeader') {
      // 套红
      const response = await getCurrentRedHeaderDocuments()
      if (response.code === 200) {
        const list = response.data || []
        // 如果有搜索条件，前端过滤
        const filteredList = searchForm.value.title
          ? list.filter((item: any) => item.title?.includes(searchForm.value.title))
          : list

        documentList.value = filteredList
        pagination.value.total = filteredList.length
      }
    } else if (activeTab.value === 'seal') {
      // 签章
      const response = await getCurrentSealDocuments()

      if (response.code === 200) {
        const list = response.data || []
        // 如果有搜索条件，前端过滤
        const filteredList = searchForm.value.title
          ? list.filter((item: any) => item.title?.includes(searchForm.value.title))
          : list

        documentList.value = filteredList
        pagination.value.total = filteredList.length
      }
    } else if (activeTab.value === 'distribute') {
      // 分发 - 查询已完结且未分发的公文（只查当前用户的）
      const userInfo = UserManager.getFullUserInfo()
      const applicantId = userInfo.id ? Number(userInfo.id) : undefined

      const params: DocumentQueryParams = {
        current: pagination.value.current,
        size: pagination.value.size,
        applicantId: applicantId, // ✅ 关键：只查询当前用户的公文
        title: searchForm.value.title || undefined,
        state: 0, // 已完结
        isDistributed: 0, // 未分发
      }

      const response = await getAllDocumentsall(params)
      if (response.code === 200) {
        documentList.value = response.data.records || []
        pagination.value.total = response.data.total || 0
      }
    }
  } catch (error: any) {
    uni.showToast({
      title: error.message || '加载数据失败',
      icon: 'none',
    })
  } finally {
    loading.value = false
  }
}

// 加载用户菜单权限
const loadUserMenuPaths = async () => {
  try {
    const { getRoleNamesByUserId } = await import('@/Api/role')
    const response = await getRoleNamesByUserId()

    if (response.code === 200 && response.data) {
      userMenuPaths.value = response.data
      console.log('[loadUserMenuPaths] 当前用户菜单权限:', userMenuPaths.value)
    } else {
      // API调用失败，使用默认权限（显示所有tab）
      userMenuPaths.value = [
        '/document',
        '/document/draft',
        '/document/todo',
        '/document/approval',
        '/document/red-header',
        '/document/seal',
        '/document/distribute',
      ]
      console.warn('[loadUserMenuPaths] 获取用户菜单权限失败，使用默认权限')
    }
  } catch (error) {
    console.error('[loadUserMenuPaths] 获取用户菜单权限失败:', error)
    // 异常情况，使用默认权限
    userMenuPaths.value = [
      '/document',
      '/document/draft',
      '/document/todo',
      '/document/approval',
      '/document/red-header',
      '/document/seal',
      '/document/distribute',
    ]
  }
}

// uni-app页面生命周期：接收页面参数
onLoad((options) => {
  console.log('[onLoad] 接收到页面参数:', options)
  pageOptions.value = options || {}
})

onMounted(async () => {
  console.log('[onMounted] 页面加载开始')

  // 确保用户信息存在
  await UserManager.ensureUserInfo()

  // 先加载用户菜单权限
  await loadUserMenuPaths()

  // 使用 onLoad 接收到的页面参数
  console.log('[onMounted] 使用的页面参数:', pageOptions.value)

  // 如果URL中指定了tab，优先使用URL参数
  if (pageOptions.value.tab) {
    const requestedTab = pageOptions.value.tab as
      | 'my'
      | 'todo'
      | 'redHeader'
      | 'seal'
      | 'distribute'
    console.log(`[onMounted] URL指定tab: ${requestedTab}`)

    // 检查请求的tab是否有权限
    const hasPermission = availableTabs.value.some((tab) => tab.key === requestedTab)
    if (hasPermission) {
      activeTab.value = requestedTab
      console.log(`[onMounted] ✅ 成功切换到URL指定的tab: ${activeTab.value}`)
    } else {
      console.warn(`[onMounted] ⚠️ URL指定的tab(${requestedTab})无权限，使用默认tab`)
      if (availableTabs.value.length > 0) {
        activeTab.value = availableTabs.value[0].key as
          | 'my'
          | 'todo'
          | 'redHeader'
          | 'seal'
          | 'distribute'
      }
    }
  } else {
    console.log('[onMounted] URL未指定tab，使用默认tab: my')
  }

  // 加载数据
  if (availableTabs.value.length > 0) {
    console.log(`[onMounted] 🎯 最终激活的tab: ${activeTab.value}`)
    loadData()
  } else {
    // 没有任何权限
    console.warn('[onMounted] 用户没有任何发文相关权限')
    uni.showToast({
      title: '暂无访问权限',
      icon: 'none',
    })
  }
})

// 页面显示时刷新数据（从详情页返回时会触发）
onShow(() => {
  console.log('[onShow] 页面显示，刷新当前tab数据:', activeTab.value)

  // 如果有权限，刷新当前tab的数据
  if (availableTabs.value.length > 0) {
    loadData()
  }
})
</script>

<style lang="scss" scoped>
.send-page {
  height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;

  /* 顶部导航 */
  .nav-header {
    background: #1678ff;
    padding: 46px 32rpx 20rpx 32rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: white;
    flex-shrink: 0;

    .nav-left {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .back-icon {
        font-size: 40rpx;
        font-weight: bold;
      }
    }

    .nav-center {
      flex: 1;
      text-align: center;

      .nav-title {
        font-size: 36rpx;
        font-weight: bold;
      }
    }

    .nav-right {
      min-width: 22px;
      .save-btn {
        font-size: 28rpx;
        padding: 12rpx 24rpx;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 12rpx;
      }
    }
  }

  /* 搜索区域 */
  .search-section {
    margin: 0 32rpx 16rpx;
    padding: 24rpx 32rpx;
    background: white;
    position: relative;
    z-index: 3;
    border-radius: 12rpx;

    .search-form {
      display: flex;
      align-items: center;
      gap: 16rpx;

      .search-input {
        flex: 1;
        height: 80rpx;
        padding: 0 24rpx;
        border: 1rpx solid #e5e7eb;
        border-radius: 12rpx;
        font-size: 28rpx;
        background: #f8f9fa;
      }

      .search-buttons {
        display: flex;
        gap: 16rpx;

        .search-btn,
        .reset-btn {
          padding: 16rpx 32rpx;
          border-radius: 12rpx;
          font-size: 26rpx;
          text-align: center;
        }

        .search-btn {
          background: #1678ff;
          color: white;
        }

        .reset-btn {
          background: #f3f4f6;
          color: #666;
        }
      }
    }
  }

  /* Tab 切换 */
  .tab-switch {
    margin-bottom: 16rpx;

    .tab-scroll {
      white-space: nowrap;
    }

    .tab-list {
      display: flex;
      gap: 16rpx;
      background: white;
      padding: 8rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);

      .tab-item {
        flex: 1;
        padding: 16rpx 24rpx;
        text-align: center;
        border-radius: 8rpx;
        transition: all 0.3s ease;
        display: flex;
        align-items: center;
        justify-content: center;

        &.active {
          background: #1678ff;
          box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);

          .tab-text {
            color: white;
          }
        }

        .tab-text {
          font-size: 28rpx;
          font-weight: 500;
          color: #666;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }

  /* 状态切换 */
  .status-switch {
    padding: 0 32rpx 16rpx;
    display: flex;
    gap: 16rpx;

    .status-tab {
      flex: 1;
      padding: 20rpx;
      background: white;
      border-radius: 12rpx;
      text-align: center;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 12rpx;

      &.active {
        background: #1678ff;
        box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.4);

        .tab-icon,
        .tab-text {
          color: white;
        }
      }

      .tab-icon {
        font-size: 28rpx;
        color: #666;
      }

      .tab-text {
        font-size: 28rpx;
        font-weight: 500;
        color: #666;
      }
    }
  }

  /* 统计信息 */
  .stats-info {
    padding: 24rpx 32rpx;
    flex-shrink: 0;

    .stat-item {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-radius: 16rpx;
      padding: 24rpx 32rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);

      .stat-label {
        font-size: 28rpx;
        color: rgba(255, 255, 255, 0.9);
        font-weight: 500;
      }

      .stat-value {
        font-size: 40rpx;
        font-weight: bold;
        color: white;
      }
    }
  }

  /* 筛选标签 */
  .filter-section {
    padding: 0 32rpx 24rpx;

    .filter-scroll {
      white-space: nowrap;

      .filter-tags {
        display: flex;
        gap: 16rpx;

        .filter-tag {
          padding: 16rpx 32rpx;
          background: white;
          border-radius: 24rpx;
          border: 1rpx solid #e5e7eb;
          transition: all 0.3s ease;

          &.active {
            background: #1a3582;
            border-color: #1a3582;

            text {
              color: white;
            }
          }

          text {
            font-size: 26rpx;
            color: #6b7280;
          }
        }
      }
    }
  }

  /* 列表区域 */
  .list-section {
    flex: 1;
    overflow: hidden;
    padding: 0 32rpx 32rpx;
    display: flex;
    flex-direction: column;

    .list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24rpx;

      .list-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }

      .list-count {
        font-size: 24rpx;
        color: #999;
      }
    }

    .loading-state {
      text-align: center;
      padding: 60rpx 0;

      .loading-text {
        font-size: 28rpx;
        color: #999;
      }
    }

    .send-list {
      flex: 1;
      overflow-y: auto;

      .send-item {
        background: white;
        border-radius: 16rpx;
        padding: 24rpx;
        margin-bottom: 16rpx;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
        transition: all 0.3s ease;

        &:active {
          opacity: 0.8;
        }

        .item-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16rpx;

          .item-title {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 12rpx;
            flex-wrap: wrap;

            .title-text {
              font-size: 28rpx;
              font-weight: 600;
              color: #333;
              flex: 1;
              min-width: 0;
            }

            .category-badge {
              padding: 6rpx 16rpx;
              border-radius: 8rpx;
              font-size: 20rpx;
              background: #ecf5ff;
              border: 1px solid #d9ecff;
              flex-shrink: 0;

              .badge-text {
                color: #1890ff;
                font-size: 20rpx;
              }
            }

            .category-badge-party {
              padding: 6rpx 16rpx;
              border-radius: 8rpx;
              font-size: 20rpx;
              background: #f0f9eb;
              border: 1px solid #e1f3d8;
              flex-shrink: 0;

              .badge-text {
                color: #67c23a;
                font-size: 20rpx;
              }
            }
          }

          .item-time {
            font-size: 22rpx;
            color: #ccc;
            flex-shrink: 0;
            margin-left: 4px;
          }
        }

        .item-content {
          margin-bottom: 16rpx;

          .item-desc {
            display: block;
            font-size: 24rpx;
            color: #999;
            line-height: 1.5;
            margin-bottom: 6rpx;
          }
        }

        .item-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .item-info {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 16rpx;
            flex-wrap: wrap;

            .reject-badge {
              padding: 6rpx 16rpx;
              border-radius: 8rpx;
              font-size: 20rpx;
              background: #fef0f0;
              border: 1px solid #fde2e2;
              flex-shrink: 0;

              .badge-text {
                color: #f56c6c;
                font-size: 20rpx;
              }
            }

            .info-text {
              font-size: 22rpx;
              color: #ccc;
            }

            .distribute-status {
              padding: 6rpx 16rpx;
              border-radius: 8rpx;
              background: #f5f5f5;
              border: 1px solid #e5e5e5;
              display: flex;
              align-items: center;
              flex-shrink: 0;

              &.distributed {
                background: #e8f5e9;
                border: 1px solid #d4edda;

                .status-text {
                  color: #2e7d32;
                }
              }

              .status-text {
                font-size: 20rpx;
                color: #999;
              }
            }
          }

          .item-actions {
            display: flex;
            gap: 20rpx;

            .action-btn {
              padding: 10rpx 20rpx;
              border-radius: 8rpx;
              font-size: 30rpx;
              color: #666;
              background: #f5f7fa;
              display: flex;
              align-items: center;
              justify-content: center;

              &.success {
                background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
                color: white;
              }

              &.primary {
                background: #1678ff;
                color: white;
              }

              &.warning {
                background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
                color: white;
              }

              &.danger {
                background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
                color: white;
              }

              &.info {
                background: linear-gradient(135deg, #30cfd0 0%, #330867 100%);
                color: white;
              }
            }
          }
        }
      }
    }

    .empty-state {
      text-align: center;
      padding: 80rpx 0;

      .empty-icon {
        font-size: 80rpx;
        display: block;
        margin-bottom: 24rpx;
      }

      .empty-text {
        font-size: 28rpx;
        color: #999;
      }
    }

    /* 分页 */
    .pagination-section {
      margin-top: 32rpx;
      padding: 24rpx;
      background: white;
      border-radius: 16rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .pagination-info {
        font-size: 24rpx;
        color: #666;
      }

      .pagination-buttons {
        display: flex;
        gap: 16rpx;

        .page-btn {
          padding: 12rpx 24rpx;
          border-radius: 12rpx;
          font-size: 24rpx;
          background: #f3f4f6;
          color: #666;

          &.disabled {
            opacity: 0.5;
            background: #f9fafb;
          }
        }
      }
    }
  }
}
</style>
